class NhanVien < ActiveRecord::Base

  attr_accessible :Email, :MaNV, :MaCV_id, :password, :password_confirmation, :new_password, :new_password_confirmation, :remember_me, :TenNV, :NgaySinh, :GioiTinh
  attr_accessor  :password, :new_password, :previous_email, :previous_username, :remember_me
  before_save :encrypt_password

  belongs_to :chuc_vu, :class_name => "ChucVu", :foreign_key => "MaCV_id"
  has_many :thoi_khoa_bieus

  validates_confirmation_of :password

  validates_presence_of :MaNV, :TenNV, :NgaySinh, :GioiTinh, :Email, :ChucVu, :password, :on => :create
  validates_length_of :password, :minimum => 6, :on => :create

  validates_uniqueness_of :MaNV, :Email

  # validate mật khẩu mới trùng khớp (khi đổi mật khẩu)
  validates_confirmation_of :new_password, :if => Proc.new { |user|
    !user.new_password.nil? && !user.new_password.empty? }
  validates_length_of :new_password, :minimum => 6, :if => Proc.new { |user|
    !user.new_password.nil? && !user.new_password.empty? }

  # validate sự duy nhất của Email khi đổi Email
  validates_uniqueness_of :Email, :if => Proc.new { |user|
    user.previous_email.nil? || user.Email != user.previous_email }

  validates_presence_of :Email, :if => Proc.new { |user|
    user.previous_email.nil? || user.Email != user.previous_email }


  #validates_presence_of(:TenNV,:ChucVu)
  #validates_uniqueness_of(:MaNV , :TenNV)


  has_many :phieu_nhaps, :class_name => "PhieuNhap"
  has_many :quan_lies, :class_name => "QuanLy"
  has_many :phieu_nhaps, :class_name => "PhieuNhap"
  has_many :phieu_xuats, :class_name => "PhieuXuat"




  # hàm truyền mảng dữ liệu thông qua format csv    EXPORT
  def self.to_csv(nhanviens, options = {}) # đối số nhanviens, gọi option để truyền vào từng cột trong excel
    CSV.generate(options) do |csv|
      csv << column_names
      nhanviens.each do |nv|
        csv << nv.attributes.values_at(*column_names)
      end
    end
  end

  # hàm truyền dữ liệu gọi lên vào database          IMPORT
  def self.import(file)
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      nhanvien = find_by_id(row["id"]) || new
      nhanvien.attributes = row.to_hash.slice(*accessible_attributes)
      return false if nhanvien.invalid?
      nhanvien.save!
    end
    true
  end

  # hàm truy xuất file upload lên
  def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
      when '.csv' then
        Roo::Csv.new(file.path, nil, :ignore)
      when ".xls" then
        Roo::Excel.new(file.path, nil, :ignore)
      when '.xlsx' then
        Roo::Excelx.new(file.path, nil, :ignore)
      else
        raise "Unknown file type: #{file.original_filename}"
    end
  end


  # Test OK
  def encrypt_password
    if password.present?
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
    end
  end

  # Test OK
  def self.authenticate_by_email(email, password)
    user = NhanVien.find_by_Email(email)
    if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
      user
    else
      nil
    end
  end

  # Test OK
  def self.authenticate_by_username(username, password)
    user = NhanVien.find_by_MaNV(username)
    if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
      user
    else
      nil
    end
  end

  def initialize(attributes = {})
    super # must allow the active record to initialize!
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def update(attributes = {})
    super # must allow the active record to initialize!
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

end
